<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" v-show="showSearch" :inline="true" label-width="68px">
      <el-form-item label="关键字" prop="keyword">
        <el-input v-model="queryParams.keyword" placeholder="请输入名称/编码" clearable style="width: 240px"
          @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete">删除</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 表格数据 -->
    <el-table v-loading="loading" :data="categoriesList" @selection-change="handleSelectionChange"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }" row-key="id">
      <!-- <el-table-column type="selection" width="55" align="center" /> -->
      <el-table-column label="名称" prop="name" width="120" />
      <el-table-column label="编码" prop="code" :show-overflow-tooltip="true" width="150" />
      <el-table-column label="简称" prop="shortName" :show-overflow-tooltip="true" width="150" />
      <el-table-column label="所属公司" prop="cName" />
      <el-table-column label="前台显示" prop="frontShow">
        <template #default="scope">
          <dict-tag :options="front_show" :value="scope.row.frontShow" />
        </template>

      </el-table-column>
      <el-table-column label="排序" prop="orderNo">
      </el-table-column>
      <el-table-column label="创建时间" prop="createTime" width="200">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="描述" prop="note" width="300" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-tooltip content="新增" placement="top" v-if="scope.row.roleId !== 1">
            <el-button link type="primary" icon="Plus" @click="handleAdd(scope.row)"></el-button>
          </el-tooltip>
          <el-tooltip content="修改" placement="top" v-if="scope.row.roleId !== 1">
            <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"></el-button>
          </el-tooltip>
          <el-tooltip content="删除" placement="top" v-if="scope.row.roleId !== 1">
            <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"></el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改流程分类对话框 -->
    <el-dialog :title="title" v-model="open" width="600px" append-to-body>
      <el-form ref="categoryRef" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-form-item :span="24" label="名称" prop="name" style="width: 100%;">
            <el-input v-model="form.name" placeholder="请输入名称" maxlength="200" />
          </el-form-item>
          <el-col :span="24">
            <el-form-item label="编码" prop="code">
              <el-input v-model="form.code" placeholder="请输入编码" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="简称" prop="shortName">
              <el-input v-model="form.shortName" placeholder="请输入简称" maxlength="200" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="所属公司" prop="companyId">
              <el-cascader v-model="form.companyId" :options="deptOptions" style="width: 100%;"
                :props="{ checkStrictly: true, value: 'value' }" ref="tree" popper-append-to-body></el-cascader>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="排序号" prop="orderNo">
              <el-input v-model="form.orderNo" placeholder="请输入排序号" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="状态" prop="frontShow">
              <el-switch v-model="form.frontShow" active-value="0" inactive-value="1" active-text="显示"
                inactive-text="隐藏" inline-prompt></el-switch>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="描述" prop="note">
              <el-input v-model="form.note" type="textarea" placeholder="请输入描述"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import { ref, reactive } from 'vue';
import { getCategories, saveOrUpdate, deleteByIds } from '@/api/base/category';
import { listDept } from '@/api/system/dept';
const { proxy } = getCurrentInstance();
const { front_show } = proxy.useDict("front_show");
const categoriesList = ref([])
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const deptOptions = ref("")
const data = reactive({
  form: {},
  queryParams: {
    keyword: ""
  },
  rules: {
    name: [{ required: true, message: "名称不能为空", trigger: "blur" }],
    code: [{ required: true, message: "编码不能为空", trigger: "blur" }],
    companyId: [{ required: true, message: "名称不能为空", trigger: "blur" }],
    //排序号必须为数字，不能有字符
    orderNo: [
      { required: true, message: "排序号不能为空", trigger: "blur" },
      { pattern: /^[0-9]*$/, message: "排序号必须为数字", trigger: "blur" }
    ],
  },
});

const { queryParams, form, rules } = toRefs(data);
/** 查询角色列表 */
function getList() {
  loading.value = true;
  getCategories(queryParams.value).then(response => {
    loading.value = false
    categoriesList.value = setTreeData(response.data);
  }).catch(res => { loading.value = false });
}
/** 搜索按钮操作 */
function handleQuery() {
  getList();
}
/** 重置按钮操作 */
function resetQuery() {
  dateRange.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}
/** 重置新增的表单以及其他数据  */
function reset() {
  form.value = {
    name: null,
    code: null,
    shortName: null,
    companyId: null,
    orderNo: null,
    frontShow: null,
    note: null,
    pid: null
  };
  proxy.resetForm("categoryRef");
}
/** 新增按钮操作 */
function handleAdd(row) {
  reset()
  open.value = true;
  title.value = "新增流程分类";
  console.log('row', row)
  if (row) {
    form.value.pid = row.id
    title.value = `新增${row.name}的流程子分类`;
  }
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value;
  getItem(_id).then((response) => {
    form.value = response.data;
    open.value = true;
    title.value = "修改流程分类";
  });
}
/** 删除按钮操作 */
function handleDelete(row) {
  const ids = [row.id] || ids.value;
  proxy.$modal.confirm('是否确认删除角色编号为"' + ids + '"的数据项?').then(function () {
    return deleteByIds(ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => { });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["categoryRef"].validate(valid => {
    if (valid) {
      form.value.companyId = form.value.companyId.join(",")
      saveOrUpdate(form.value).then(response => {
        open.value = false;
        getList();
      })
    }
  });
}
/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}

/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

function getDeptList() {
  listDept().then(response => {
    const deptData = response.data.map(item => ({
      value: item.deptId,
      label: item.deptName,
      parentId: item.parentId,
    }))
    deptOptions.value = proxy.handleTree(deptData, "value");
  });
}

function setTreeData(list) {
  let templist = []
  list.forEach(item => {
    if (!item.pid) {
      templist.push(item)
    }
    else {
      let index = templist.findIndex(i => i.id == item.pid)
      if (index != -1) {
        templist[index].children = templist[index].children || []
        templist[index].children.push(item)
      }
    }
  })
  return templist
}
getList();
getDeptList();
</script>
